package demo;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:恋恋
 * Date:2022-09-20
 * Time:16:38
 */
class Age implements Cloneable{
   public int a=10;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Animal implements Cloneable{//标记当前类是可以克隆的
    public String name;
    Age age=new Age();

    public Animal(String name) {
        this.name = name;
    }

    public void work(){
        System.out.println(this.name+"工作");
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
      Animal animal=(Animal) super.clone();//首先浅层拷贝
        animal.age=(Age) this.age.clone();//其次是深层拷贝
        return animal;
    }
}

public class Test {
    public static void main(String[] args)throws CloneNotSupportedException {
        Animal animal1=new Animal("Helloword");
        Animal animal2=(Animal) animal1.clone();
        System.out.println(animal1==animal2);
        System.out.println("======修改animal1中Age对象的a之前=====");
        System.out.println("aniaml1中的a"+animal1.age.a);
        System.out.println("aniaml2中的a"+animal2.age.a);
        animal1.age.a=500;//修改
        System.out.println("=====修改之后=====");
        System.out.println("aniaml1中的a"+animal1.age.a);
        System.out.println("aniaml2中的a"+animal2.age.a);
    }
}
